package com.lzs.bootsafety.common.base.controller;

import com.lzs.bootsafety.business.sys.entity.SysUser;
import com.lzs.bootsafety.business.sys.service.*;
import com.lzs.bootsafety.common.util.CheckIsNull;
import com.lzs.bootsafety.common.util.Resu;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class BaseController {
    @Autowired
    protected SysMenuService sysMenuService;
    @Autowired
    protected SysUserService sysUserService;
    @Autowired
    protected SysRoleService sysRoleService;
    @Autowired
    protected SysPostService sysPostService;
    @Autowired
    protected SysDeptService sysDeptService;
    protected CheckIsNull checkIsNull = new CheckIsNull();
    protected Resu respAdd(int row){
        return row > 0 ? Resu.suces("添加成功"): Resu.error("添加失败");
    }
    protected Resu respudp(int row){
        return row > 0 ? Resu.suces("更新成功"): Resu.error("更新失败");
    }
    protected Resu respDel(int row){
        return row > 0 ? Resu.suces("删除成功"): Resu.error("删除失败");
    }
    @InitBinder
    public void initBinder(WebDataBinder binder){
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    protected Logger log = LoggerFactory.getLogger(getClass());

    protected SysUser getUser() {
        return (SysUser) SecurityUtils.getSubject().getPrincipal();
    }
    protected Session getSession(){
        return SecurityUtils.getSubject().getSession();
    }
    protected Long getUserId() {
        return getUser().getUserId();
    }
    protected String getUserName() {
        return getUser().getUsername();
    }
    protected Date  date(){
        return new Date();
    }

    public static String  validateResult(BindingResult bindingResult){
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        return allErrors.get(0).getDefaultMessage();
    }
}
